package com.it.jasypt.controller;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.it.jasypt.dto.UserEntity;
import com.it.jasypt.dto.UserDTO;
import org.springframework.beans.BeanUtils;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class UserService extends ServiceImpl<UserMapper, UserEntity> {
    @Resource
    private PasswordEncoder passwordEncoder;

    public UserDTO getUserById(Long id) {
        UserEntity userEntity = this.getById(id);
        if (userEntity == null) {
            return null;
        }
        UserDTO dto = new UserDTO();
        BeanUtils.copyProperties(userEntity, dto);
        return dto;
    }

    public Long createUser(UserDTO userDTO) {
        UserEntity userEntity = new UserEntity();
        BeanUtils.copyProperties(userDTO, userEntity);

        // 加密密码
        userEntity.setPassword(passwordEncoder.encode(userDTO.getPassword()));

        // 保存用户
        this.save(userEntity);
        return userEntity.getId();
    }

    public boolean updateUser(UserDTO userDTO) {
        UserEntity userEntity = new UserEntity();
        BeanUtils.copyProperties(userDTO, userEntity);
        return this.updateById(userEntity);
    }
}